<template>
    <div class="main">
        <a-form name="custom-validation" ref="formRef" :model="formState" :rules="rules" v-bind="layout" @keypress.enter="handleSubmit">
            <a-form-item required has-feedback name="username">
                <a-input placeholder="账号" v-model:value="formState.username" autocomplete="off">
                    <template #prefix>
                        <UserOutlined />
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item required has-feedback name="password">
                <a-input placeholder="密码" v-model:value="formState.password" type="password" autocomplete="off">
                    <template #prefix>
                        <LockOutlined />
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item>
                <a-button :loading="loading" type="primary" block @click="handleSubmit">登录</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>
<script setup lang="ts">
import { useStore } from 'vuex';
import { notification } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import md5 from 'md5';
import { reactive, ref, UnwrapRef } from 'vue';
interface FormState {
    username: string;
    password: string;
}
const router = useRouter();
const store = useStore();
const loading = ref(false);
const formRef = ref();
const formState: UnwrapRef<FormState> = reactive({
    username: '',
    password: ''
});
const rules = {
    username: [{ required: true, message: '用户名不能为空', trigger: 'change' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'change' }]
};
const layout = {
    wrapperCol: { span: 24 }
};
const loginSuccess = () => {
    router.replace({ path: '/' });
};
const handleSubmit = async () => {
    const res = await formRef.value.validate();
    if (res) {
        loading.value = true;
        const password = md5(md5(formState.password));
        const query = {
            username: formState.username,
            password
        };
        store.dispatch('user/Login', query).then((res) => {
            loading.value = false;
            if (res.success) {
                loginSuccess();
            } else {
                notification.error({
                    message: '登陆失败',
                    description: res.errorMsg
                });
            }
        });
    }
};
</script>
<style lang="less" scoped>
::v-deep(.ant-btn) {
    border-color: transparent !important;
}
::v-deep(.ant-btn-block) {
    background: #1890ff !important;
    color: #fff;
}
</style>
